const http = require('http');
const querystring = require('querystring');

const crypto = require('crypto');
const secret = 'ahhh123';

http.createServer((req, res) => {
    req.getCookie = function (key, options = {}) {
        let value = querystring.parse(req.headers.cookie, '; ', '=')[key] || '';
        console.log('value:',value);
        if (value) {
            if (options.signed){
                let [realValue, sign] = value.split('.');
                const newSign = crypto.createHmac('sha256', secret).update(realValue + '').digest('base64').replace(/\/|\+|\=/g,'');
                if(sign === newSign){
                    console.log(1);
                    return realValue;
                }else{
                    console.log(2);
                    return '';
                }
            }
        }else{
            return '';
        }
    };

    const arr = [];
    res.setCookie = function (key, value, options={}) {
        const args = [];
        if(options.httpOnly){
            args.push(`httpOnly=true`);
        }
        if(options.maxAge){
            args.push(`max-age=${options.maxAge}`);
        }
        if(options.signed){
            const sign = crypto.createHmac('sha256', secret).update(value + '').digest('base64').replace(/\/|\+|\=/g,'')/* 设置的时候是没有问题，但接受cookie的时候可能+、_、-等会丢失 变成' ' */;
            value = value + '.' + sign;
        }
        arr.push(`${key}=${value}; ${args.join('; ')}`); // xingming=ahhh  age=123
        res.setHeader('Set-Cookie',arr)
    };

    if(req.url === '/read'){
        res.end(req.getCookie('xingming',{signed: true}));
    }

    if(req.url === '/write'){
        res.setCookie('xingming', 'ahhh', {httpOnly:true,maxAge:1000, signed: true});
        res.setCookie('age', '123');
        return res.end('write ok');
    }

    res.end('not found');
}).listen(3000);
//Set-Cookie: xingming=ahhh.eDIudcCHodGUPPuIJdXzaI430r14Wfs0JoBWZtvts; httpOnly=true; max-age=1000